package top.hidoctor.auscultation.feature.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Queue;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.utils.BlueToothDataUtils;
import top.hidoctor.auscultation.utils.BlueToothUtils;
import top.hidoctor.auscultation.utils.GetJsonDataUtil;
import top.hidoctor.auscultation.utils.HexUtil;
import top.hidoctor.auscultation.utils.MyInternalStorage;
import top.hidoctor.auscultation.utils.WavHeader;
import top.hidoctor.auscultation.widget.mark.MyHScrollView;

import static top.hidoctor.auscultation.feature.activity.DeviceActivity.BLUETOOTH_DEVICE;
import static top.hidoctor.auscultation.utils.BlueToothUtils.getBlueToothUtils;

public class TestActivity2 extends BaseActivity {


    private static final int WRITE_SUC = 0x001;
    private static final int WRITE_FAIL = 0x002;
    private static final int SWITCH_OFF = 0x003;
    private static final int ADD_LIST = 0x005;
    private static final int YIN_DAO = 0x006;
    // 暂存本地的数据
    private List<String> localList = new ArrayList<>();
    private ArrayList<Float> pointList = new ArrayList<>();//储存的点集合
    private BluetoothGatt bluetoothGatt;

    private AudioTrack tracker;
    private MyHScrollView hScrollView;
    private LinearLayout llEcg;
    private LinearLayout llEcgContent;
    private Chronometer timer;
    private Button btn;
    private Button btnStop;
    private boolean isRecord = false;
    private BlueToothUtils blueToothUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_test2);
        initView();
        initEvent();
    }

    private void initEvent() {

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                blueToothUtils.write("a600a600");
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                blueToothUtils.write("ad00ad00");
            }
        });
        int bufferSize = AudioTrack.getMinBufferSize(frequency, channelOutConfig, audioEncoding);

        tracker = new AudioTrack(AudioManager.STREAM_MUSIC, frequency, channelOutConfig, audioEncoding, bufferSize * 2, AudioTrack.MODE_STREAM);//录音播放


        BluetoothDevice device = getIntent().getParcelableExtra(BLUETOOTH_DEVICE);
        blueToothUtils = getBlueToothUtils();
        blueToothUtils.setSetMtu(true);
        bluetoothGatt = blueToothUtils.connect(device, this);
        blueToothUtils.setBlueToothHandle(new BlueToothUtils.BlueToothHandle() {
            @Override
            public void getCharacteristicChanged(byte[] data) {

                //  这里将蓝牙传过来的数据转换为 16 进制格式的字符串
                if (data.length > 5) {
                    final byte[] bytes = Arrays.copyOfRange(data, 6, data.length - 2);
                    for (int i = 0; i < top.hidoctor.auscultation.utils.HexUtil.encodeHexStr(bytes).length() - 1; i += 4) {
                        Float point = BlueToothDataUtils.getComplement(top.hidoctor.auscultation.utils.HexUtil.encodeHexStr(bytes).substring(i, i + 4));
                        pointList.add(point);
                    }
                    String s = BlueToothDataUtils.transformData(top.hidoctor.auscultation.utils.HexUtil.encodeHexStr(bytes));
                    bufferQueue.offer(top.hidoctor.auscultation.utils.HexUtil.hexStringToBytes(s));
                    Log.i("TAG", "处理后: " + top.hidoctor.auscultation.utils.HexUtil.encodeHexStr(bytes));
                } else {//
                    if (top.hidoctor.auscultation.utils.HexUtil.encodeHexStr(data).equals("ad0000ad00")) {//停止接受
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isRecord = false;
                                if (timer != null) {
                                    timer.stop();
                                }
//                                if (pointTimer != null) {
//                                    pointTimer.cancel();
//                                }
//                                if (moveTimer != null) {
//                                    moveTimer.cancel();
//                                }
                            }
                        }, 1000);
                    }
                }


                Log.i("TAG", "原数据： " + HexUtil.encodeHexStr(data));

            }

            @Override
            public void stateDisconnected() {
            }

            @Override
            public void stateDisconnecting() {

            }

            @Override
            public void stateConnected() {

            }

            @Override
            public void stateConnecting() {

            }

            @Override
            public void characteristicWrite(int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    mHandler.sendEmptyMessage(WRITE_SUC);
                } else {
                    mHandler.sendEmptyMessage(WRITE_FAIL);
                }
            }

            @Override
            public void startWrite() {

            }
        });
    }

    private void initView() {

        hScrollView = findViewById(R.id.h_scrollView);
        llEcg = findViewById(R.id.ll_ecg);
        llEcgContent = findViewById(R.id.ll_ecg_content);
        timer = findViewById(R.id.timer);
        btn = findViewById(R.id.btn);
        btnStop = findViewById(R.id.btn_stop);
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WRITE_SUC://写入成功
                    if (btn.getText().equals("开始采集")) {
                        btn.setText("结束采集");
                    } else {
                        btn.setText("开始采集");
                    }
                    break;
                case WRITE_FAIL://写入失败

                    break;
                case SWITCH_OFF://断开
                    btn.setText("开始采集");
                    break;
                case ADD_LIST:
                    ArrayList<Float> list = new ArrayList<>();
                    list.addAll((List<Float>) msg.obj);
                    Log.e("TAG", "handleMessage: " + list.size());
                    ArrayList<Float> newList = new ArrayList<>();
                    for (int i = 0; i < list.size(); i += 40) {
                        newList.add(list.get(i));
                    }
//                    addEcgView(newList);
                    pointList.clear();
                    break;
            }
        }
    };


    // 采样率
    private int frequency = 8000;
    // 采样通道
    private int channelInConfig = AudioFormat.CHANNEL_IN_MONO;
    // 播放通道 单声道
    private int channelOutConfig = AudioFormat.CHANNEL_OUT_MONO;
    // 16位音频编码
    private int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
    // 录音缓存区
//    private byte[] bufferIn = null;

    // 存放录音缓存的队列
    private Queue<byte[]> bufferQueue = null;


    //同步录音播放
    private class RecordPlayingRunnable implements Runnable {

        @Override
        public void run() {
            tracker.play();
            while (true) {
                if (bluetoothGatt == null) {
                    return;
                }
                byte[] bufferOut = bufferQueue.poll();
                if (bufferOut != null && tracker != null) {
                    tracker.write(bufferOut, 0, bufferOut.length);
                }
                if (!isRecord) { //停止录音 弹出循环
                    return;
                }
            }
        }
    }
}
